package com.song.codesandbox.backups;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.dfa.FoundWord;
import cn.hutool.dfa.WordTree;
import com.song.codesandbox.CodeSandBox;
import com.song.codesandbox.model.*;
import com.song.codesandbox.utils.ProcessUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;

@Slf4j
public class JavaNativeCodeSandBox implements CodeSandBox {

    /**
     * 全局代码存放目录
     */
    private static final String GLOBAL_CODE_DIR_NAME = "TmpCode";

    /**
     * 全局代码文件名
     */
    private static final String GLOBAL_JAVA_CLASS_NAME = "Main.java";

    /**
     * 超时时间，单位：毫秒
     */
    private static final long TIME_OUT = 5000L;

    /**
     * 敏感词
     */
    private static final List<String> blackList = Arrays.asList("File", "exec");

    /**
     * 敏感词字典树
     */
    private static final WordTree wordTree = new WordTree();

    /**
     * 初始化敏感词字典树
     */
    static {
        wordTree.addWords(blackList);
    }

    /**
     * 执行代码
     *
     * @param request
     * @return
     */
    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest request) {
        List<String> inputList = request.getInputList();
        String code = request.getCode();
        String language = request.getLanguage();
        if (inputList == null || inputList.isEmpty() || StrUtil.isBlank(code) || StrUtil.isBlank(language)) {
            return createErrorResponse(new IllegalArgumentException("参数不合法"));
        }
        return executeCode(request.getInputList(), request.getCode(), request.getLanguage());
    }

    /**
     * 执行代码
     *
     * @param inputList 程序的输入
     * @param code      程序要执行的代码
     * @param language  编程语言
     * @return
     */
    @Override
    public ExecuteCodeResponse executeCode(List<String> inputList, String code, String language) {

        /**
         * 1. 程序编译与执行的前置准备
         * - 代码校验
         * - 创建用户代码编译与运行的临时目录
         */
        codeVerify(code);

        String userDir = System.getProperty("user.dir");
        String globalCodePathName = userDir + File.separator + GLOBAL_CODE_DIR_NAME;
        // 判断全局代码目录是否存在，如果不存在则新建目录
        if (!FileUtil.exist(globalCodePathName)) {
            FileUtil.mkdir(globalCodePathName);
        }

        /**
         * 2. 为用户生成独立的代码存放文件夹，将用户的代码隔离存放
         */
        String userCodeParentPath = globalCodePathName + File.separator + UUID.randomUUID();
        String userCodePath = userCodeParentPath + File.separator + GLOBAL_JAVA_CLASS_NAME;
        File userCodeFile = FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);

        /**
         * 3. 编译代码，保存.class文件
         */
        log.info("---------代码编译开始---------");
        String compileCmd = String.format("javac -encoding utf-8 %s", userCodeFile.getAbsoluteFile());
        log.info("编译命令: {}", compileCmd);
        ExecuteMessage compileExecuteMessage = new ExecuteMessage();
        try {
            Process compileProcess = Runtime.getRuntime().exec(compileCmd);
            compileExecuteMessage = ProcessUtils.runProcess(compileProcess, ProcessExecType.COMPILE);
        } catch (IOException e) {
            return createErrorResponse(e);
        }

        log.info("---------代码编译结束---------");


        log.info("---------代码执行开始---------");
        /**
         * 4. 代码执行, 获取执行结果
         * 注：由于代码可能有多组输入，故而可能会有多组输出
         */
        List<ExecuteMessage> runExecuteMessageList = new ArrayList<>();
        for (String arg : inputList) {
            String codeRunCmd = String.format("java -Xmx256m -Dfile.encoding=UTF-8 -cp %s Main %s", userCodeParentPath, arg);
            log.info("执行命令: {}", codeRunCmd);
            try {
                Process runProcess = Runtime.getRuntime().exec(codeRunCmd);
                ProcessUtils.timeoutMonitor(runProcess, TIME_OUT);
                ExecuteMessage executeMessage = ProcessUtils.runProcess(runProcess, ProcessExecType.RUN);
                runExecuteMessageList.add(executeMessage);
            } catch (Exception e) {
                return createErrorResponse(e);
            }
        }
        log.info("---------代码执行结束---------");

        /**
         * 5. 整理输出，构造代码执行的响应结果
         * (1) 输出结果: outputList
         * (2) 接口信息: message
         * (3) 执行状态: status
         *      1: 执行成功
         *      2: 异常
         *      3: 执行失败
         * (5) 判题信息: judgeInfo
         *    判题信息包括：程序执行信息(message)、消耗时间(time)以及消耗内存(memory)
         */
        ExecuteCodeResponse response = new ExecuteCodeResponse();
        List<String> outputList = new ArrayList<>();
        long maxTime = 0L;
        // 遍历所有执行信息
        for (ExecuteMessage executeMessage : runExecuteMessageList) {
            String errorMessage = executeMessage.getErrorMessage();
            if (StrUtil.isNotBlank(errorMessage)) {
                response.setMessage(errorMessage);
                response.setStatus(3);
                break;
            }
            outputList.add(executeMessage.getMessage());
            if (executeMessage.getTime() != null) {
                maxTime = Math.max(maxTime, executeMessage.getTime());
            }
        }

        if (outputList.size() == runExecuteMessageList.size()) {
            response.setStatus(1);
        }
        response.setOutputList(outputList);
        JudgeInfo judgeInfo = new JudgeInfo();
        judgeInfo.setTime(maxTime);
        response.setJudgeInfo(judgeInfo);

        /**
         * 6. 文件清理, 防止服务器空间不足
         */
        if (userCodeFile.getParentFile() != null) {
            boolean del = FileUtil.del(userCodeFile.getParentFile());
            log.info("删除{}", (del ? "成功" : "失败"));
        }

        return response;
    }

    /**
     * 构建异常错误响应
     *
     * @param e 异常状态
     * @return 异常错误响应
     */
    private ExecuteCodeResponse createErrorResponse(Throwable e) {
        ExecuteCodeResponse response = new ExecuteCodeResponse();
        response.setOutputList(new ArrayList<>());
        response.setMessage(e.getMessage());
        response.setStatus(2);
        response.setJudgeInfo(new JudgeInfo());
        return response;
    }

    /**
     * 代码校验: 检测代码中是否有不合法的内容
     * 缺点:
     * - 无法遍历所有的黑名单
     * - 不同的编程语言, 对应的领域、关键词都不一样, 限制成本很大
     *
     * @param code
     */
    private void codeVerify(String code) {
        FoundWord foundWord = wordTree.matchWord(code);
        if (Objects.nonNull(foundWord) && StrUtil.isNotBlank(foundWord.getFoundWord())) {
            log.info("检测到非法字符: {}", foundWord.getFoundWord());
            throw new RuntimeException("检测到非法字符：" + foundWord.getFoundWord());
        }
    }


    /**
     * 执行代码示例
     *
     * @param args
     */
    public static void main(String[] args) {
        JavaNativeCodeSandBox javaNativeCodeSandBox = new JavaNativeCodeSandBox();

        String code = ResourceUtil.readStr("test/unSafeCode/ReadFileError.java", StandardCharsets.UTF_8);
        ExecuteCodeRequest request = ExecuteCodeRequest.builder()
                .inputList(Arrays.asList("1 2", "3 4"))
                .code(code)
                .language("java")
                .build();

        ExecuteCodeResponse response = javaNativeCodeSandBox.executeCode(request);
    }
}
